package com.bjpowernode.seckillweb.service.impl;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.seckillweb.service.GoodsService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 查询全部参与秒杀的商品信息
     * @return
     */
    @Override
    public List<Goods> queryGoosList() {

        //存储所有的商品信息
        List<Goods> goodsList = new ArrayList<>();

        //从redis中查询数据 先模糊查询出key
        Set<String> keys = redisTemplate.keys(Constants.REDIS_GOODS + "*");

        //根据key获取对应的value
        keys.forEach(key -> {
            Goods goods = (Goods) redisTemplate.opsForValue().get(key);

            //将随机码设置为null，防止提前暴露
            goods.setRandomName(null);

            goodsList.add(goods);
        });

        return goodsList;
    }


    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @Override
    public Goods getById(Integer id) {

        Goods goods = (Goods)redisTemplate.opsForValue().get(Constants.REDIS_GOODS + id);

        return goods;
    }
}
